package com.cat.gridChart;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/coloring-a-border/description/
 * @create 2025/9/6 21:00
 * @since JDK17
 */

public class Solution06 {
    int[][] g, d = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
    int r, c, color;
    boolean[][] vis;
    void dfs(int x, int y) {
        vis[x][y] = true;
        for (int i = 0; i < 4; i++) {
            int nx = x + d[i][0], ny = y + d[i][1];
            if (nx == -1 || nx == r || ny == -1 || ny == c || !vis[nx][ny]) {
                return;
            }
            if (g[x][y] != g[nx][ny]) {
                g[x][y] = color;
            } else {
                dfs(nx, ny);
            }
        }
        if (x == 0 || x == r - 1 || y == 0 || y == c - 1) {
            g[x][y] = color;
        }
    }

    public int[][] colorBorder(int[][] grid, int row, int col, int color) {
        r = grid.length;
        c = grid[0].length;
        g = grid;
        this.color = color;
        vis = new boolean[r][c];
        dfs(row, col);
        return g;
    }
}
